<template>
    <div ref="refLiquid"></div>
</template>

<script setup lang="ts">
import { Liquid, measureTextWidth } from '@antv/g2plot'
import type { Datum } from '@antv/g2plot'
import { onMounted, ref } from 'vue'

const refLiquid = ref<HTMLElement>()
const liquidPlot = ref<Liquid>()

function LiquidRender() {
    if (!refLiquid.value) return
    liquidPlot.value = new Liquid(refLiquid.value, {
        percent: 0.26,
        radius: 0.8,
        statistic: {
            title: {
                formatter: () => '盈利率',
                style: ({ percent }) => ({
                    fill: percent > 0.65 ? 'white' : 'rgba(44,53,66,0.85)',
                }),
            },
            content: {
                style: ({ percent }): Datum => ({
                    fontSize: 60,
                    lineHeight: 1,
                    fill: percent > 0.65 ? 'white' : 'rgba(44,53,66,0.85)',
                }),
                customHtml: (container, view, el) => {
                    const { percent } = el as Datum
                    const { width, height } = container.getBoundingClientRect()
                    const d = Math.sqrt(Math.pow(width / 2, 2) + Math.pow(height / 2, 2))
                    const text = `占比 ${(percent * 100).toFixed(0)}%`
                    const textWidth = measureTextWidth(text, { fontSize: 60 })
                    const scale = Math.min(d / textWidth, 1)
                    return `<div style="width:${d}px;display:flex;align-items:center;justify-content:center;font-size:${scale}em;line-height:${
                        scale <= 1 ? 1 : 'inherit'
                    }">${text}</div>`
                },
            },
        },
        liquidStyle: ({ percent }) => {
            return {
                fill: percent > 0.45 ? '#5B8FF9' : '#FAAD14',
                stroke: percent > 0.45 ? '#5B8FF9' : '#FAAD14',
            }
        },
        color: () => '#5B8FF9',
    })
    liquidPlot.value.render()
}
onMounted(() => {
    LiquidRender()

    let data = 0.25
    const interval = setInterval(() => {
        data += Math.min(Math.random() * 0.1, 0.1)
        if (data < 0.75) {
            ;(liquidPlot.value as Liquid).changeData(data)
        } else {
            clearInterval(interval)
        }
    }, 500)
})
</script>